<!DOCTYPE html>
<html>

<head>
  <title>Background Sync API Instrumentation Test</title>
  <script src="../notifications/notification_test_utils.js"></script>
</head>

<body>
  <!-- This method is used by the BackgroundSyncTest instrumentation test. -->
  <h1>Background_Sync_API_Instrumentation_Test</h1>
  <script>
    function GetActivatedServiceWorkerForTest() {
      return GetActivatedServiceWorker('service_worker.js', location.pathname);
    }

    function SetupReplyForwardingForTests() {
      GetActivatedServiceWorkerForTest()
        .then(registration => {
          const replyListener = event => {
            if (event.data.startsWith('onsync: ') || event.data.startsWith('onperiodicsync: ') || event.data.startsWith('failed periodicsync: ')) {
              messagePort.removeEventListener('message', replyListener);
              sendToTest(event.data);
            }
          };
          messagePort.addEventListener('message', replyListener);
        })
        .catch(sendToTest);
    }

    function RegisterSyncForTag(tag) {
      navigator.permissions.query({ name: 'background-sync' })
        .then(result => {
          if (result.state !== 'granted') {
            // 'background-sync' permission should be granted by default.
            sendToTest('permission denied');
            return;
          }

          GetActivatedServiceWorkerForTest()
            .then(registration => {
              registration.sync.register(tag)
                .then(() => sendToTest('registered sync'));
            });
        })
        .catch(sendToTest);
    }

    function RegisterPeriodicSyncForTag(tag) {
      GetActivatedServiceWorkerForTest()
        .then(registration => {
          registration.periodicSync.register(tag)
            .then(() => sendToTest('registered periodicsync'));
        })
        .catch(sendToTest);
    }

    function UnregisterPeriodicSyncForTag(tag) {
      GetActivatedServiceWorkerForTest()
        .then(registration => {
          registration.periodicSync.unregister(tag)
            .then(() => sendToTest('unregistered periodicsync'));
        })
        .catch(sendToTest);
    }

    // BackgroundSyncTest observes changes to the tab title as an
    // asynchronous response mechanism from JavaScript to Java.
    function sendToTest(message) {
      document.title = message;
    }
  </script>
</body>

</html>
